# 店铺信息管理
import time

from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import Shop
from django.core.paginator import Paginator
from django.db.models import Q  # 或条件
from datetime import datetime
import random


# Create your views here.
def index(request, pIndex=1):
    """ 浏览信息 """
    # smod = Shop.objects
    slist = Shop.objects.filter(status__lt=9)

    # 搜索条件
    mywhere = []
    kw = request.GET.get('keyword', None)
    if kw:
        slist = slist.filter(name__contains=kw)
        mywhere.append('keyword=' + kw)
    # status = request.GET.get('status', '')
    # if kw:
    #     slist = slist.filter(status=status)
    #     mywhere.append('status=' + status)

    slist = slist.order_by('id')  # 排序

    # 分页处理
    pIndex = int(pIndex)
    page = Paginator(slist, 5)  # 5条数据一页显示
    maxpages = page.num_pages  # 获取最大页数
    # 判断不能越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页数据
    plist = page.page_range  # 获取页码列表信息
    context = {
        'shoplist': list2,
        'plist': plist,
        'pIndex': pIndex,
        'maxpages': maxpages,
        'mywhere': mywhere
    }
    return render(request, 'myadmin/shop/index.html', context)


def add(request):
    """ 添加 """
    return render(request, 'myadmin/shop/add.html')


from utils.encrypt import md5
from utils.encrypt import add_salt


def insert(request):
    """ 执行添加 """
    try:
        # 图片上传
        myfile = request.FILES.get('cover_pic', None)
        print(myfile.name)
        if not myfile:
            return HttpResponse('没有上传店铺封面文件信息')
        cover_pic = str(time.time()) + '.' + myfile.name.split('.').pop()
        with open('./static/uploads/shop/' + cover_pic, mode='wb+') as f:
            for chunk in myfile.chunks():  # 分块写入文件
                f.write(chunk)
        f.close()

        myfile1 = request.FILES.get('banner_pic', None)
        # print(myfile1.name)
        if not myfile1:
            return HttpResponse('没有上传店铺logo文件信息')
        banner_pic = str(time.time()) + '.' + myfile1.name.split('.').pop()
        with open('./static/uploads/shop/' + banner_pic, mode='wb+') as f:
            for chunk in myfile1.chunks():  # 分块写入文件
                f.write(chunk)
        f.close()

        ob = Shop()
        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']
        ob.cover_pic = cover_pic
        ob.banner_pic = banner_pic
        ob.status = 1
        ob.create_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ob.save()
        context = {'info': '添加成功'}
    except Exception as arr:
        print(arr)
        context = {'info': '添加失败'}

    return render(request, 'myadmin/info.html', context)


def delete(request, sid=0):
    """ 删除 """
    # print(sid)
    try:
        ob = Shop.objects.get(id=sid)
        ob.status = 9
        ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ob.save()
        context = {'info': '删除成功'}
    except Exception as arr:
        print(arr)
        context = {'info': '删除失败'}

    return render(request, 'myadmin/info.html', context)


def edit(request, sid=0):
    """ 编辑 """
    try:
        ob = Shop.objects.get(id=sid)
        context = {'shop': ob}
        return render(request, 'myadmin/shop/edit.html', context)

    except Exception as arr:
        print(arr)
        context = {'info': '没有找到要修改的信息'}
        return render(request, 'myadmin/info.html', context)


def update(request, sid=0):
    """ 执行编辑 """
    print(sid)
    try:
        ob = Shop.objects.get(id=sid)
        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        ob.save()
        context = {'info': '修改成功'}
    except Exception as arr:
        print(arr)
        context = {'info': '修改失败'}

    return render(request, 'myadmin/info.html', context)
